/**
 * @file system.c
 * @author your name (you@domain.com)
 * @brief
 * @version 0.1
 * @date 2025-01-13
 *
 * @copyright Copyright (c) 2025
 *
 */
#include "system.h"

/**
 * @brief get system time info
 * 
 * @param time_info 
 * @param in_time_ms 
 */
void System_DevTime(system_time_t *time_info, uint64_t in_time_ms)
{
    uint64_t ms = in_time_ms % (uint64_t)1000;
    uint64_t second = in_time_ms / (uint64_t)1000;
    uint64_t minute = second / (uint64_t)60;
    uint64_t hour = minute / (uint64_t)60;
    uint64_t day = hour / (uint64_t)24;

    second %= 60;
    minute %= 60;
    hour %= 24;

    if (time_info)
    {
        time_info->day = (uint32_t)day;
        time_info->hour = (uint32_t)hour;
        time_info->min = (uint32_t)minute;
        time_info->sec = (uint32_t)second;
        time_info->ms = (uint32_t)ms;
    }
}

/**
 * @brief get system time 
 * 
 * @param day_p 
 * @param hour_p 
 * @param minute_p 
 * @param second_p 
 * @param System_TickGet 
 */
void System_Time(uint32_t *day_p, uint32_t *hour_p, uint32_t *minute_p, uint32_t *second_p, uint32_t (*System_TickGet)(void))
{
    static uint32_t time_last = 0;
    static uint32_t time_base = 0;

    uint32_t time_curr = 0;
    uint64_t time;

    if (System_TickGet)
    {
        time_curr = System_TickGet();
    }

    if (time_base == 0)
    {
        time_base = (time_curr < time_last) ? 0xFFFFFFFFU : 0;
        time_last = time_curr;
    }
    time = time_base + time_curr;

    uint64_t second = time / (uint64_t)1000;
    uint64_t minute = second / (uint64_t)60;
    uint64_t hour = minute / (uint64_t)60;
    uint64_t day = hour / (uint64_t)24;

    second %= 60;
    minute %= 60;
    hour %= 24;

    if (day_p && hour_p && minute_p && second_p)
    {
        *day_p = (uint32_t)day;
        *hour_p = (uint32_t)hour;
        *minute_p = (uint32_t)minute;
        *second_p = (uint32_t)second;
    }
}